﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Lib.Core
{

    /// <summary>
    /// int intValue1               = "123".ConvertTo<int>();
    /// int? intValue2              = "123".ConvertTo<int?>();           
    /// DateTime dateTimeValue1     = "1981-08-24".ConvertTo<DateTime>();
    /// DateTime? dateTimeValue2    = "1981-08-24".ConvertTo<DateTime?>();
    /// </summary>
    public static class ConvertToExtensions
    {
        public static T ConvertTo<T>(this IConvertible convertibleValue)
        {
            if (null == convertibleValue)
            {
                return default(T);
            }

            if (!typeof(T).IsGenericType)
            {
                return (T) Convert.ChangeType(convertibleValue, typeof(T));
            }
            else
            {
                Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Nullable<>))
                {
                    return (T) Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
                }
            }

            throw new InvalidCastException(string.Format("Invalid cast from type \"{0}\" to type \"{1}\".",
                convertibleValue.GetType().FullName, typeof(T).FullName));
        }
    }
}
